<?php

namespace app\admin\controller;

use app\admin\controller\appForm\Reviews;
use app\admin\model\Picture;
use think\Db;

class AppForm extends Backend
{

    protected $model = null;
    protected $with = ['user', 'seal', 'approval'];

    private $sealModel = null;
    private $configModel = null;

    protected $beforeActionList = [
        'getCurrentCompany'
    ];

    use Reviews;

    public function _initialize()
    {
        $this->model = new \app\admin\model\AppForm();
        $this->sealModel = new \app\admin\model\Seal();
        $this->configModel = new \app\admin\model\Config();
        parent::_initialize();
    }

    public function add()
    {

        $company_id = $this->company->id;
        $uid = $this->getCurrentUser();

        //用户所属部门ID集合
        $department_id = Db::name('staff')->where(['uid' => $uid, 'company_id' => $company_id])->value('department_id');
        $department_id_arr = explode(',', $department_id);

        // 上次提交选择的审批类型id
        $prev_app_id = Db::name('app_form')->where(['uid' => $uid])->order('id desc')->value('app_id');

        //这个公司所有的印章ID集合
        $seal_list = Db::name('seal')->field('id,name,department')->where(['company_id' => $company_id, 'is_del' => 0])->order('id desc')->select();

        $seal_id_arr = [];
        foreach ($seal_list as &$v) {
            $approval_list = Db::name('approval')->field('id,type_name,is_free')->where(['seal_id' => $v['id'], 'is_del' => 0])->order('id desc')->select();
            $v['approval_list'] = $approval_list ? : [];

            //印章所属部门ID集合
            $department_arr = explode(',', $v['department']);
            //两个数组之间有没有相同的值，可以申请这个印章
            if (array_intersect($department_arr, $department_id_arr)) $seal_id_arr[] = $v['id'];
        }

        if ($seal_id_arr) $prev_seal_id = Db::name('app_form')->where(['uid' => $uid])->order('id desc')->value('seal_id');

        $this->assign('seal_list', json_encode($seal_list));
        $this->assign('prev_seal_id', $prev_seal_id ? : 0);
        $this->assign('prev_app_id', $prev_app_id ? : 0);
        $this->assign('company_id', $company_id);
        $this->assign('uid', $uid);

        $this->assign('title', '新增申请');
        return $this->fetch();
    }

    /**
     * 列表页
     * @return mixed
     */
    public function index()
    {
        $sealAppFormStatues = $this->configModel->getSealAppFormStatues();
        //$seals = $this->sealModel->scope('company', $this->company->id)->select();
        $condition['is_del'] = ['eq', 0];
        $condition['company_id'] = $this->company->id;
        $seals = db('seal')->where($condition)->select();
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $where = [];
        $params = $this->request->param();
        if ($params['status']) {
            $where['status'] = $params['status'];
        } else {
            $where['status'] = ['lt', 5];
        }
        if ($params['sealId']) {
            $where['seal_id'] = $params['sealId'];
        }

        //$where['uid'] = $this->getCurrentUser();
        //$where['company_id'] = $this->company->id;
        if (session('is_admin') == 3) {
            $where['uid'] = $this->getCurrentUser();
            $where['company_id'] = $this->company->id;
        } elseif (session('is_admin') == 2) {
            //企业管理员
            $where['company_id'] = $this->company->id;
        } else {
            $where['company_id'] = $this->company->id;
        }
        //		print_r($where);die;
        $list = $this->model
            ->with($this->with ? $this->with : null)
            ->where($where)
            //->where('status', '<>', 5)
            ->order($sort, $order)
            ->paginate($limit);
        $this->assign('params', $params);
        $this->assign('seals', $seals);
        $this->assign('statuses', $sealAppFormStatues);
        $this->assign('list', $list);
        return $this->fetch();
    }

    public function dc()
    {
        $sealAppFormStatues = $this->configModel->getSealAppFormStatues();
        //$seals = $this->sealModel->scope('company', $this->company->id)->select();
        $condition['is_del'] = ['eq', 0];
        $condition['company_id'] = $this->company->id;
        $seals = db('seal')->where($condition)->select();
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $where = [];
        $params = $this->request->param();
        if ($params['status']) {
            $where['status'] = $params['status'];
        } else {
            $where['status'] = ['lt', 5];
        }
        if ($params['sealId']) {
            $where['seal_id'] = $params['sealId'];
        }

        //$where['uid'] = $this->getCurrentUser();
        //$where['company_id'] = $this->company->id;
        if (session('is_admin') == 3) {
            $where['uid'] = $this->getCurrentUser();
            $where['company_id'] = $this->company->id;
        } elseif (session('is_admin') == 2) {
            //企业管理员
            $where['company_id'] = $this->company->id;
        } else {
            $where['company_id'] = $this->company->id;
        }

        $list = $this->model
            ->with($this->with ? $this->with : null)
            ->where($where)
            //            ->where('status', '<>', 5)
            ->order($sort, $order)
            ->select();

        if ($list) {
            foreach ($list as &$v) {
                $v['apply_username'] = Db::name('user')->where(['id' => $v['uid']])->value('username');
                $v['approval_username'] = getApprovalUsername($v['id']);
                $v['carbon_username'] = getCarbonUsername($v['id']);
            }
        }

        vendor('phpexcel/PHPExcel');
        //3.实例化PHPExcel类
        $objPHPExcel = new \PHPExcel();
        //var_dump($objPHPExcel);exit;
        //4.激活当前的sheet表
        $objPHPExcel->setActiveSheetIndex(0);
        //5.设置表格头（即excel表格的第一行）
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '申请项目')
            ->setCellValue('B1', '审批类型')
            ->setCellValue('C1', '文件名称')
            ->setCellValue('D1', '文件编号')
            ->setCellValue('E1', '申请人')
            ->setCellValue('F1', '审核人')
            ->setCellValue('G1', '抄送人')
            ->setCellValue('H1', '申请时间')
            ->setCellValue('I1', '用章时间')
            ->setCellValue('J1', '实际次数')
            ->setCellValue('K1', '状态')
            ->setCellValue('L1', '备注');

        //设置A列水平居中
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //设置单元格宽度
        //6.循环刚取出来的数组，将数据逐一添加到excel表格。
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('A')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('C')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('D')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('E')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('F')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('G')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('H')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('I')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('J')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('K')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('L')->setWidth(20);

        for ($i = 0; $i < count($list); $i++) {
            $objPHPExcel->getActiveSheet()->setCellValue('A' . ($i + 2), $list[$i]['seal']['name']);
            $objPHPExcel->getActiveSheet()->setCellValue('B' . ($i + 2), $list[$i]['approval']['type_name']);
            $objPHPExcel->getActiveSheet()->setCellValue('C' . ($i + 2), $list[$i]['name']);
            $objPHPExcel->getActiveSheet()->setCellValue('D' . ($i + 2), $list[$i]['file_number']);
            $objPHPExcel->getActiveSheet()->setCellValue('E' . ($i + 2), $list[$i]['apply_username']);
            $objPHPExcel->getActiveSheet()->setCellValue('F' . ($i + 2), $list[$i]['approval_username']);
            $objPHPExcel->getActiveSheet()->setCellValue('G' . ($i + 2), $list[$i]['carbon_username']);
            $objPHPExcel->getActiveSheet()->setCellValue('H' . ($i + 2), $list[$i]['create_time']);
            $objPHPExcel->getActiveSheet()->setCellValue('I' . ($i + 2), $list[$i]['chapter_time'] ? date('Y-m-d H:i:s', $list[$i]['chapter_time']) : '');
            $objPHPExcel->getActiveSheet()->setCellValue('J' . ($i + 2), $list[$i]['use_count']);
            $objPHPExcel->getActiveSheet()->setCellValue('K' . ($i + 2), $list[$i]['status_txt']);
            $objPHPExcel->getActiveSheet()->setCellValue('L' . ($i + 2), $list[$i]['remark']);
        }
        //7.设置保存的Excel表格名称
        $filename = 'yz' . date('ymd', time()) . '.xls';
        //8.设置当前激活的sheet表格名称；
        $objPHPExcel->getActiveSheet()->setTitle('cs');
        //9.设置浏览器窗口下载表格
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="' . $filename . '"');
        //生成excel文件
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        //下载文件在浏览器窗口
        $objWriter->save('php://output');
        exit;
    }

    /**
     * 列表页
     * @return mixed
     */
    public function archiveIndex()
    {
        $sealAppFormStatues = $this->configModel->getSealAppFormStatues();
        //$seals = $this->sealModel->scope('company', $this->company->id)->select();
        $condition['is_del'] = ['eq', 0];
        $condition['company_id'] = $this->company->id;
        $seals = db('seal')->where($condition)->select();
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $where = [];
        $params = $this->request->param();
        if ($params['status']) {
            $where['status'] = $params['status'];
        }
        if ($params['sealId']) {
            $where['seal_id'] = $params['sealId'];
        }
        //$where['uid'] = $this->getCurrentUser();
        //$where['company_id'] = $this->company->id;

        if (session('is_admin') == 3) {
            $where['uid'] = $this->getCurrentUser();
            $where['company_id'] = $this->company->id;
        } elseif (session('is_admin') == 2) {
            //企业管理员
            $where['company_id'] = $this->company->id;
        } else {
            $where['company_id'] = $this->company->id;
        }


        $where['status'] = 5;
        $list = $this->model
            //            ->hasWhere('processFlows', ['uid' => $this->getCurrentUser()])
            ->with($this->with ? $this->with : null)
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $this->assign('params', $params);
        $this->assign('seals', $seals);
        $this->assign('statuses', $sealAppFormStatues);
        $this->assign('list', $list);

        return $this->fetch();
    }

    public function dc1()
    {
        $sealAppFormStatues = $this->configModel->getSealAppFormStatues();
        //$seals = $this->sealModel->scope('company', $this->company->id)->select();
        $condition['is_del'] = ['eq', 0];
        $condition['company_id'] = $this->company->id;
        $seals = db('seal')->where($condition)->select();
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $where = [];
        $params = $this->request->param();
        if ($params['status']) {
            $where['status'] = $params['status'];
        }
        if ($params['sealId']) {
            $where['seal_id'] = $params['sealId'];
        }
        //$where['uid'] = $this->getCurrentUser();
        //$where['company_id'] = $this->company->id;

        if (session('is_admin') == 3) {
            $where['uid'] = $this->getCurrentUser();
            $where['company_id'] = $this->company->id;
        } elseif (session('is_admin') == 2) {
            //企业管理员
            $where['company_id'] = $this->company->id;
        } else {
            $where['company_id'] = $this->company->id;
        }


        $where['status'] = 5;

        $list = $this->model
            ->with($this->with ? $this->with : null)
            ->where($where)
            ->order($sort, $order)
            ->select();

        foreach ($list as &$v) {
            $v['status_name'] = $v['used_img'] ? '已上传图片' : '未上传图片';

            $v['apply_username'] = Db::name('user')->where(['id' => $v['uid']])->value('username');
            $v['approval_username'] = getApprovalUsername($v['id']);
            $v['carbon_username'] = getCarbonUsername($v['id']);
        }

        vendor('phpexcel/PHPExcel');
        //3.实例化PHPExcel类
        $objPHPExcel = new \PHPExcel();
        //exit($objPHPExcel);
        //4.激活当前的sheet表
        $objPHPExcel->setActiveSheetIndex(0);
        //5.设置表格头（即excel表格的第一行）
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '申请项目')
            ->setCellValue('B1', '审批类型')
            ->setCellValue('C1', '文件名称')
            ->setCellValue('D1', '文件编号')
            ->setCellValue('E1', '申请人')
            ->setCellValue('F1', '审核人')
            ->setCellValue('G1', '抄送人')
            ->setCellValue('H1', '申请时间')
            ->setCellValue('I1', '用章时间')
            ->setCellValue('J1', '实际次数')
            ->setCellValue('K1', '状态')
            ->setCellValue('L1', '备注');

        //设置A列水平居中
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //设置单元格宽度
        //6.循环刚取出来的数组，将数据逐一添加到excel表格。
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('A')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('C')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('D')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('E')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('F')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('G')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('H')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('I')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('J')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('K')->setWidth(20);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('L')->setWidth(20);

        for ($i = 0; $i < count($list); $i++) {
            $objPHPExcel->getActiveSheet()->setCellValue('A' . ($i + 2), $list[$i]['seal']['name']);
            $objPHPExcel->getActiveSheet()->setCellValue('B' . ($i + 2), $list[$i]['approval']['type_name']);
            $objPHPExcel->getActiveSheet()->setCellValue('C' . ($i + 2), $list[$i]['name']);
            $objPHPExcel->getActiveSheet()->setCellValue('D' . ($i + 2), $list[$i]['file_number']);
            $objPHPExcel->getActiveSheet()->setCellValue('E' . ($i + 2), $list[$i]['apply_username']);
            $objPHPExcel->getActiveSheet()->setCellValue('F' . ($i + 2), $list[$i]['approval_username']);
            $objPHPExcel->getActiveSheet()->setCellValue('G' . ($i + 2), $list[$i]['carbon_username']);
            $objPHPExcel->getActiveSheet()->setCellValue('H' . ($i + 2), $list[$i]['create_time']);
            $objPHPExcel->getActiveSheet()->setCellValue('I' . ($i + 2), $list[$i]['chapter_time'] ? date('Y-m-d H:i:s', $list[$i]['chapter_time']) : '');
            $objPHPExcel->getActiveSheet()->setCellValue('J' . ($i + 2), $list[$i]['use_count']);
            $objPHPExcel->getActiveSheet()->setCellValue('K' . ($i + 2), $list[$i]['status_txt']);
            $objPHPExcel->getActiveSheet()->setCellValue('L' . ($i + 2), $list[$i]['remark']);
        }
        //7.设置保存的Excel表格名称
        $filename = 'yz' . date('ymd', time()) . '.xls';
        //8.设置当前激活的sheet表格名称；
        $objPHPExcel->getActiveSheet()->setTitle('cs');
        //9.设置浏览器窗口下载表格
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="' . $filename . '"');
        //生成excel文件
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        //下载文件在浏览器窗口
        $objWriter->save('php://output');
        exit;


    }

    /**
     * 查看审核流程
     * @param $id
     */
    public function processFlows($id)
    {
        $entity = $this->model->with(['processFlows.user'])->find($id);
        if (!$entity) {
            $this->error('没有找到相关数据');
        }
        if ($this->request->ext() == 'json') {
            $this->success("成功", null, processToGroupSort($entity->processFlows));
        }
        $this->assign('processFlowGroups', processToGroupSort($entity->processFlows));
        return $this->fetch();
    }


    /**
     * 详情页面
     * @param null $id
     * @return string|void
     */
    public function show($id = null)
    {
        $row = $this->model->with(['processFlows.user', 'user', 'seal', 'approval'])->find($id);
        if (!$row) {
            $this->error("没有找到相关数据！");
        }
        if ($this->request->isAjax()) {
            $this->success("", null, $row);
        }
        $value = processToGroupSort($row->processFlows);
        $this->assign("processFlowGroups", $value);
        $this->assign("user", $row->user);
        $this->assign("seal", $row->seal);
        $this->assign("approval", $row->approval);
        $this->assign("attachments", []);
        if ($row->imgs) {
            $value1 = (new Picture())->getByIdIn(explode(",", $row->imgs));
            $this->assign("attachments", $value1);
        }
        if ($row->used_img) {
            $value2 = (new Picture())->getByIdIn(explode(",", $row->used_img));
            $this->assign("attachments2", $value2);
        }
        //print_r($value);die;
        //文档
        if ($row->file) {
            $file1 = $row->file;
            $file = explode(',', $file1);
            foreach ($file as $k => $v) {
                $bb[$k]['src'] = "https://" . $_SERVER['HTTP_HOST'] . db('picture')->where(['id' => $v])->value('path');
                $bb[$k]['name'] = db('picture')->where(['id' => $v])->value('name');
            }
            $wd = $bb;
        } else {
            $wd = '';
        }
        $this->assign("wd", $wd);

        $ll = db('approval_process')->where(['form_id' => $id])->order('id asc')->select();
        //print_r($ll);die;
        foreach ($ll as $k => $v) {
            if ($v['remark'] == 1) {
                $reason = '文件名称不全，请核实';
            } elseif ($v['remark'] == 2) {
                $reason = '用章次数可能过多，请重新设置';
            } elseif ($v['remark'] == 3) {
                $reason = '图片上传不够清晰，请核对后重新上传';
            } elseif ($v['remark'] == 4) {
                $reason = $v['remark_content'];
            }

        }
        $this->assign("reason", $reason);
        $this->assign("row", $row);
        return $this->fetch();
    }

    /**
     * 删除提交表单
     * @param $id
     */
    public function delete($id)
    {
        if ($this->request->isPost()) {
            if ($id) {
                $row = $this->model->with(['processFlows'])->get($id);
                if (!$row) {
                    $this->error("没有找到相关数据！");
                }
                if ($row->unFinished()) { //判断是否是未完成的流程
                    //进行关联删除
                    $row->together(['processFlows'])->delete();
                    $this->success("删除成功");
                }
                $this->error("该表单已经用章完成，不能删除");
            }
            $this->error();
        }
    }
}
